package com.tju.controller;

import com.tju.Result;
import com.tju.service.MsmService;
import com.tju.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信的方法
    @GetMapping("/send/{phone}")
    public Result sendMessage(@PathVariable String phone){
        //先从redis中获取验证码，如果获取到直接返回
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(redisCode)){
            return Result.ok();
        }

        //redis中取不到，进行腾讯云发送
        //生成随机值
        String code = RandomUtil.getFourBitRandom();
        boolean isSend = msmService.sendMsg(phone,code);
        if (isSend){
            //设置五分钟有效
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.error().message("短信发送失败");
        }
    }

}
